<template>
  <div class="my-dialog">
    <div
      v-drag
      class="modal_box"
      style="width: 400px; height: 300px; top: 40%; left: 40%"
      ref="dialog"
    >
      <div class="modal_header">对话框<span class="modal_close">X</span></div>
      <div class="modal_body">
        <div style="line-height: 100px; text-align: center">这是一个对话框</div>
      </div>
      <div class="modal_footer">
        <button>确定</button>
        <button>取消</button>
      </div>
    </div>
  </div>
</template>

<script>
let x = 0;
export default {
  data() {
    return {};
  },
  directives: {
    drag: function (el) {
      let dragBox = el; //获取当前元素
      dragBox.onmousedown = (e) => {
        //算出鼠标相对元素的位置
        let disX = e.clientX - dragBox.offsetLeft;
        let disY = e.clientY - dragBox.offsetTop;
        document.onmousemove = (e) => {
          //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
          let left = e.clientX - disX;
          let top = e.clientY - disY;
          //移动当前元素
          dragBox.style.left = left + "px";
          dragBox.style.top = top + "px";
        };
        document.onmouseup = (e) => {
          //鼠标弹起来的时候不再移动
          document.onmousemove = null;
          //预防鼠标弹起来后还会循环（即预防鼠标放上去的时候还会移动）
          document.onmouseup = null;
        };
      };
    },
  },
  methods: {
    mouseDown(e) {
      let dialog = this.$refs.dialog.parentNode;
      dialog.addEventListener("mousemove", this.moveFn);
      dialog.addEventListener("mousedown", this.downFn);
    },
    mouseUp(e) {
      let dialog = this.$refs.dialog.parentNode;
      dialog.removeEventListener("mousemove", this.moveFn);
      dialog.removeEventListener("mousedown", this.downFn);
    },
    moveFn(e) {
      let dialog = this.$refs.dialog;
      let left = dialog.style.left.replace("px", "") + (e.pageX - x) + "px";
      dialog.style.left = left;
      dialog.style.top = e.pageY - 20 + "px";
      x = e.pageX;
    },
    downFn(e) {
      x = e.pageX;
    },
  },
};
</script>

<style scoped>
.my-dialog {
  position: fixed;
  z-index: 99;
  height: 100%;
  width: 100%;
  border: 1px solid black;
}
.modal_box {
  background: white;
  border-radius: 4px;
  position: fixed;
  box-shadow: 0 0 3px #aaaaaa;
}

.modal_box > .modal_header {
  cursor: move;
  border-radius: 4px 4px 0 0;
  background: radial-gradient(circle, #00bfff, #1e90ff);
  height: 40px;
  line-height: 40px;
  padding: 0 16px;
  font-size: 18px;
  color: white;
}

.modal_box > .modal_header > span.modal_close {
  color: white;
  font-size: 18px;
  display: inline-block;
  cursor: pointer;
}

.modal_box > .modal_body {
  height: calc(100% - 100px);
}

.modal_box > .modal_footer {
  height: 60px;
  line-height: 60px;
  text-align: center;
}

.modal_box > .modal_footer > button {
  border: none;
  background: #1e90ff;
  color: white;
  width: 80px;
  height: 30px;
  line-height: 30px;
  border-radius: 4px;
}

.modal_box > .modal_footer > button:hover {
  background: #00bfff;
}
</style>